import { Alert, FlatList, Keyboard, StyleSheet, TouchableWithoutFeedback, View } from 'react-native'
import React, { useState } from 'react'
import Header from '../components/header'
import TodoItem from '../components/todoItem'
import AddToDo from '../components/addToDo'

interface ToDoIem {
  title: string,
  id: number
}

export default function Todo() {
  const [todo, setTodo] = useState<ToDoIem[]>([
    { title: '任务1', id: 1 },
    { title: '任务2', id: 2 },
  ])

  // 删除任务项
  const pressHandler = (id: number) => {
    setTodo((prevTodos: ToDoIem[]) => prevTodos.filter((item) => item.id !== id))
  }

  // 添加任务项
  const submitHandler = (val: string) => {
    // 判断任务标题的长度
    if (val.length > 3) {
      setTodo((prevTodos: ToDoIem[]) => {
        return [
          { title: val, id: prevTodos.length + 1 },
          ...prevTodos
        ]
      })
    } else {
      Alert.alert('信息提示', '任务名称长度必须大于3个字符', [{ text: '关闭', onPress: () => { } }])
    }
  }

  return (
    <TouchableWithoutFeedback onPress={() => {
      Keyboard.dismiss() // 关闭键盘
    }}>
      <View style={styles.container}>
        <Header />

        <View style={styles.content}>
          <AddToDo submitHandler={submitHandler} />

          <View style={styles.list} >
            <FlatList data={todo} renderItem={({ item }) => (
              <TodoItem item={item} pressHandler={pressHandler} />
            )} />
          </View>
        </View>
      </View>
    </TouchableWithoutFeedback>
  )
}

const styles = StyleSheet.create({
  container: {
  },
  content: {
    padding: 40,
    height: 600
  },
  list: {
    marginTop: 20
  }
})